﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.ComponentModel;

namespace Viinikellari
{
    [XmlRoot("viinikellari")]
   public class Winecellar : INotifyPropertyChanged
    {
        public Winecellar()
        {
            Kokoelma = new List<Wine>();
        }

        [XmlElement("wine")]        
        public List<Wine> Kokoelma {get; set;}

        public Wine ReturnWine(int i)
        {            
            Wine wine = new Wine();
            wine = Kokoelma[i];
            return wine;
        }

        public void InsertWine(Wine wine)
        {
            Kokoelma.Add(wine);
        }

        public int ReturnCount()
        {
            return Kokoelma.Count();
        }

        [XmlIgnore]
        public IEnumerable<string> Countries
        {
            get {
                yield return "";
                foreach (var c in Kokoelma.Select(s => s.Country).Distinct())
                    yield return c;
            }
        }
        [XmlIgnore]
        public IEnumerable<Wine> WinesByCountry
        {
            get
            {
                if (string.IsNullOrEmpty(SelectedCountry))
                    return Kokoelma;

            var x = Kokoelma.Where(p => p.Country == SelectedCountry);
            return x;
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        public void NotifyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        [XmlIgnore]
        string selectedCountry;
        [XmlIgnore]
        public string SelectedCountry
        {
            get { return selectedCountry; }
            set
            {
                setField(ref selectedCountry, value, "SelectedCountry");
                NotifyChanged("WinesByCountry");
            }
        }

        protected void setField<T>(ref T field, T value, string propertyName)
        {
            if (EqualityComparer<T>.Default.Equals(field, value))
                return;
            field = value;
            NotifyChanged(propertyName);
        }
    }
}
